import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import './Item.css'
import slice, { asyncTodos } from '../../redux/slice'
const { updateTodo, delTodo, setEditId, setTodoName } = slice.actions
export default function Item({ todo: { todoName, id, isDone } }) {
  const dispatch = useDispatch()
  const editId = useSelector((state) => {
    return state.zs.editId
  })

  const [tN, setTN] = useState('')
  return (
    <li>
      {editId !== id ? (
        <label>
          <input
            type="checkbox"
            checked={isDone}
            onChange={() => {
              dispatch(updateTodo(id))
            }}
          />
          <span className={isDone ? 'done' : ''}>{todoName}</span>
        </label>
      ) : (
        <input
          type="text"
          value={tN}
          onChange={(e) => {
            setTN(e.target.value.trim())
          }}
          onKeyUp={(e) => {
            if (!tN || e.key !== 'Enter') return
            dispatch(setTodoName({ id, todoName: tN }))
          }}
        />
      )}
      <button
        className="btn btn-danger"
        onClick={() => {
          // dispatch(delTodo(id)) //同步
          dispatch(asyncTodos(id)) // 异步的
        }}
      >
        删除
      </button>
      <button
        className="btn btn-edit"
        onClick={() => {
          setTN(todoName)
          dispatch(setEditId(editId !== id ? id : undefined))
        }}
      >
        {editId !== id ? '编辑' : '取消'}
      </button>
    </li>
  )
}
